<template>
  <div class="login">
    <van-nav-bar title="登录" left-arrow @click-left="$router.back()" />
    <div class="zixun">优点达资讯</div>
    <van-form @submit="login">
      <van-field
        left-icon="manager"
        v-model.number="mobile"
        name="手机号"
        label="手机号"
        :rules="rules.mobile"
      />
      <van-field
        left-icon="lock"
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        :rules="rules.password"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
    <div class="left">
      <a href="#" @click="$router.push('/register')">没有账号，立即注册</a>
    </div>
  </div>
</template>

<script>
// 导入发送登陆请求的函数
import { loginFn } from '@/api/login'
import { mapMutations } from 'vuex'
// 本地存储用户的token函数
import { setUserToken } from '@/utils/storage'
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Login',
  data() {
    return {
      // 手机号
      mobile: '13155135220',
      // 密码
      password: '123456',
      // 校验规则
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号码格式错误'
          }
        ],
        password: [{ required: true, message: '密码不能为空' }]
      }
    }
  },
  methods: {
    async login() {
      const { data: res } = await loginFn(this.mobile, this.password)
      // console.log(res)
      // 将获取到的token保存到本地以及vuex中
      // 调用vuex存储用户的token函数
      this.setUserToken(res.token)
      // 调用函数存储到本地
      setUserToken(res.token)
      this.$router.push('/user')
    },
    // vuex存储用户的token函数
    ...mapMutations('user', ['setUserToken'])
  }
}
</script>

<style lang="less" scoped>
.zixun {
  text-align: center;
  color: #1989fa;
  padding: 20px 0;
}
.left {
  display: flex;
  justify-content: flex-end;
  a {
    margin-right: 20px;
    font-size: 8px;
  }
}
</style>
